<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>工时填报</title>
    <link rel="stylesheet" href="/plugins/layui/css/layui.css" media="all">
    <link rel="stylesheet" type="text/css" href="/build/css/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/easyui.css">
    <link rel="stylesheet" type="text/css" href="/css/my-style.css">
    <style>        /* 防止下拉框的下拉列表被隐藏---必须设置--- */
    .layui-table-cell {
        overflow: visible !important;
    }

    /* 设置下拉框的高度与表格单元相同 */
    .layui-input, .layui-select, .layui-textarea {
        height: 30px !important;
    }

    </style>
</head>

<body>
<div class="kit-doc">
    <!--表格搜索框组-->
    <div class="layui-form-item layui-formgroup layui-tab-card">
        <div class="layui-inline">
            <form class="layui-form " action="">
                <input type="hidden" id="monday">
                <input type="hidden" id="sunday">
                <label class="layui-form-label">项目：</label>
                <div class="layui-input-inline">
                    <select name="project" id="searchProject" lay-verify="required" lay-search="">
                        <option value=""></option>
                        <option value="" th:each="project : ${projectList}" th:value="${project.getId()}" th:text="${project.getProjectName()}"></option>
                    </select>
                </div>
            </form>
        </div>
        <!-- 时间 -->
        <div class="layui-inline">
            <label class="layui-form-label">日期：</label>
            <div class="layui-input-inline">
                <input class="layui-input" id="test6" placeholder=" 时间段 " type="text" readonly="readonly" disabled="disabled">
            </div>
        </div>

        <!-- 按钮 -->
        <button class="layui-btn layui-btn-sm" id="searchBtn">搜索</button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="preWeekBtn">
            <i class="fa fa-reply margin-r3"></i>上一周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="thisWeekBtn">
            <i class="fa fa-search margin-r3"></i>本周
        </button>
        <button class="layui-btn layui-btn-primary layui-btn-sm" id="nextWeekBtn">
            <i class="fa fa-share margin-r3"></i>下一周
        </button>
    </div>

    <div class="layui-card layui-card-body gs-box">
        <div id="tb" style="height:auto">
            <a href="javascript:void(0)" class="easyui-linkbutton l-btn-text" id="addBtn">
                <i class="fa fa-plus"></i> 录入
            </a>
            <a href="javascript:void(0)" class="easyui-linkbutton l-btn-text" id="saveBtn">
                <i class="fa fa-check"></i> 保存
            </a>
        </div>
        <table class="layui-table xuhao-table" id="table-context" lay-filter="test">
            <script type="text/html" id="barDemo">
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
            </script>
        </table>
    </div>
</div>

<script type="text/html" id="projectTpl">
    <select name="project" id="project_{{d.id}}" lay-filter="projectSelect" lay-verify="required" lay-search="">
        <option value=""></option>
        <option value="" th:each="project : ${projectList}" th:value="${project.getId()}" th:text="${project.getProjectName()}"></option>
    </select>
</script>

<script type="text/html" id="typeTpl">
    <select name="project" id="type_{{d.id}}" lay-filter="typeSelect" lay-verify="required" lay-search="">
        <option value=""></option>
        <option value="" th:each="type : ${typeList}" th:value="${type.getId()}" th:text="${type.getTypeName()}"></option>
    </select>
</script>

<script src="/js/jquery.min.js"></script>
<script src="/plugins/layui/layui.js"></script>
<script src="/js/workhour.js"></script>
<script>
    Array.prototype.remove = function (from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
    };
</script>
<script>
    Date.prototype.format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }
    /*
     * 重写时间的toJSON方法，因为在调用JSON.stringify的时候，时间转换就调用的toJSON，这样会导致少8个小时，所以重写它的toJSON方法
     */
    Date.prototype.toJSON = function () {
        return this.format("yyyy-MM-dd hh:mm:ss"); // util.formatDate是自定义的个时间格式化函数
    };

    var now = new Date();

    // 获取周一和周末
    var start = getTime(0, now);
    $("#monday").val(start);
    var end = getTime(-6, now);
    $("#end").val(end);

    layui.use(['table', 'jquery', 'form'], function () {
        // 保存上次查询的数据
        var table = layui.table;
        var $ = layui.$;
        var form = layui.form;
        var projectTable = table.render({
            elem: '#table-context'
            , url: '/workhours/view/me'
            , height: 'full-200'
            , page: true
            , limit: 10
            , limits: [10, 20, 30]
            , request: {
                pageName: 'page' //页码的参数名称，默认：page
                , limitName: 'size' //每页数据量的参数名，默认：limit
            }
            , cols: [
                [
                    {
                        field: 'projectId',
                        title: '项目名称',
                        templet: '#projectTpl',
                        width: '10%',
                        align: 'center'
                    }, //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
                    {
                        field: 'projectTypeId',
                        title: '项目类型',
                        templet: '#typeTpl',
                        width: '10%',
                        align: 'center'
                    },
                    {
                        field: 'remark',
                        title: '任务信息',
                        edit: 'text',
                        align: 'center'
                    },
                    {
                        field: 'workDate',
                        title: '工作日期',
                        width: '6%'
                    },
                    {
                        field: 'mon',
                        edit: 'text',
                        title: '周一',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'tues',
                        edit: 'text',
                        title: '周二',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'wed',
                        edit: 'text',
                        title: '周三',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'thur',
                        edit: 'text',
                        title: '周四',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'fri',
                        edit: 'text',
                        title: '周五',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'stat',
                        edit: 'text',
                        title: '周六',
                        width: '4%',
                        align: 'center'
                    },
                    {
                        field: 'sun',
                        edit: 'text',
                        title: '周日',
                        align: 'center',
                        width: '4%'
                    },
                    {
                        title: '操作',
                        fixed: 'right',
                        align: 'center',
                        width: '5%',
                        toolbar: '#barDemo'
                    }
                ]
            ]
            , done: function (res, curr, count) {
                $("table tr").find("td:eq(2)").css("overflow","hidden")
                ///让表格中的select默认选中
                for (var i = 0; i < res.data.length; i++) {
                    $("#project_" + res.data[i].id).val(res.data[i].projectId);//atype是select的id
                    $("#type_" + res.data[i].id).val(res.data[i].projectTypeId);//atype是select的id
                }
                form.render('select');
            }
        });

        // 保存是否被编辑
        var isEdit = false;

        /**
         * 下拉选择项目名称
         */
        form.on('select(projectSelect)', function (obj) {
            // layer.msg("data=" + obj.elem.getAttribute('name') + '：' + obj.value + ' ' + obj.elem);
            var index = $(obj.elem).parent().parent().parent().index();
            var tableData = table.cache["table-context"];
            tableData[index].projectId = obj.value;
            isEdit = true;
        });

        form.on('select(typeSelect)', function (obj) {
            // layer.msg("data=" + obj.elem.getAttribute('name') + '：' + obj.value + ' ' + obj.elem);
            var index = $(obj.elem).parent().parent().parent().index();
            var tableData = table.cache["table-context"];
            tableData[index].projectTypeId = obj.value;
            isEdit = true;
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'del') {
                layer.confirm('确定删除当前行？', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    layer.close(index);
                    if (!isEmpty(data.id)) {
                        //向服务端发送删除指令
                        layui.$.ajax({
                            type: 'DELETE',
                            url: "/workhours/del/" + data.id,
                            success: function (res) {
                                layer.closeAll();
                                if (res.code == 0) {
                                    layer.msg("删除成功");
                                    refresh()
                                } else {
                                    layer.msg("修改失败" + res.msg);
                                }
                            }
                        });
                    } else {
                        var str = obj.tr.selector;
                        str = str.substring(str.indexOf("\"") + 1, str.lastIndexOf("\""));
                        var tableData = table.cache["table-context"];
                        tableData.remove(str);
                        table.cache["table-context"] = tableData;
                    }
                });
            }
        });

        //监听单元格编辑
        table.on('edit(test)', function (obj) {
            isEdit = true;

        });

        // 添加数据
        $("#addBtn").click(function () {
            isEdit = true;
            var newRow = {
                id: null,
                projectId: null,
                projectTypeId: null,
                userId: null,
                workDate: null,
                workHours: null,
                delFlag: null,
                fri: null,
                mon: null,
                remark: null,
                stat: null,
                sun: null,
                thur: null,
                tues: null,
                wed: null
            };

            var oldData = table.cache["table-context"];
            oldData.push(newRow);
            projectTable.reload({
                url: "",
                data: oldData
            });
        });

        /**
         * 搜索
         */
        $("#searchBtn").click(function () {
            refresh();
        });

        function refresh(){
            var searchProjectContext = $("#searchProject").val();
            var start = $("#test6").val().split(' - ')[0];
            var end = $("#test6").val().split(' - ')[1];

            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: searchProjectContext,
                    startDate: start,
                    endDate: end
                }
            });
        }

        // 保存操作
        $("#saveBtn").click(function () {
            if (isEdit) {
                // 获取表格数据
                var tableData = table.cache["table-context"];
                var monDate = new Date($("#monday").val());

                for (var i = 0; i < tableData.length; i++) {
                    var rowData = tableData[i];
                    // 一周是否只填写了一天
                    var isOne = false;
                    if (!isEmpty(rowData.mon)) {
                        rowData.workHours = rowData.mon;
                        rowData.workDate = monDate;
                        isOne = true;
                    }
                    if (!isEmpty(rowData.tues)) {
                        rowData.workHours = rowData.tues;
                        rowData.workDate = addDate(monDate, 1);
                        isOne = !isOne;
                    }
                    if (!isEmpty(rowData.wed)) {
                        rowData.workHours = rowData.wed;
                        rowData.workDate = addDate(monDate, 2);
                        isOne = !isOne;
                    }
                    if (!isEmpty(rowData.thur)) {
                        rowData.workHours = rowData.thur;
                        rowData.workDate = addDate(monDate, 3);
                        isOne = !isOne;
                    }
                    if (!isEmpty(rowData.fri)) {
                        rowData.workHours = rowData.fri;
                        rowData.workDate = addDate(monDate, 4);
                        isOne = !isOne;
                    }
                    if (!isEmpty(rowData.stat)) {
                        rowData.workHours = rowData.stat;
                        rowData.workDate = addDate(monDate, 5);
                        isOne = !isOne;
                    }
                    if (!isEmpty(rowData.sun)) {
                        rowData.workHours = rowData.sun;
                        rowData.workDate = addDate(monDate, 6);
                        isOne = !isOne;
                    }
                    if (isEmpty(rowData.projectId)) {
                        layer.msg("第" + (i + 1) + "行,请选择项目名称！");
                        return;
                    }
                    if (isEmpty(rowData.projectTypeId)) {
                        layer.msg("第" + (i + 1) + "行,请选择项目类型！");
                        return;
                    }
                    if (isEmpty(rowData.remark)) {
                        layer.msg("第" + (i + 1) + "行,工作任务不能为空！");
                        return;
                    }
                    if (!isOne || isNaN(parseFloat(rowData.workHours))) {
                        layer.msg("第" + (i + 1) + "行,工时填写有误，请检查后再保存");
                        return;
                    }
                    if (isNaN(parseFloat(rowData.workHours))) {
                        layer.msg("第" + (i + 1) + "行,工作时间填写有误！，请检查后再保存");
                        return;
                    }
                }

                //批量增加修改
                $.ajax({
                    type: 'POST',
                    url: "/workhours/add",
                    contentType: "application/json",
                    dataType: 'json',
                    data: JSON.stringify(tableData),
                    success: function (res) {
                        layer.closeAll();
                        if (res.code == 0) {
                            projectTable.reload({
                                url: '/workhours/view/me',
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            })
                            layer.msg("保存成功！");
                        } else {
                            layer.msg("保存失败！" + res.msg);
                        }
                    }
                })
            } else {
                layer.msg("请编辑行！");
            }
        });

        // 上一周
        $("#preWeekBtn").click(function () {
            var monDate = $("#monday").val();
            var preMon = dateToStr(addDate(monDate, -7));
            var preSun = dateToStr(addDate(monDate, -1));
            $("#monday").val(preMon);
            $("#sunday").val(preSun);
            $("#test6").val(preMon + ' - ' + preSun);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: preMon,
                    endDate: preSun
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })

        });

        // 下一周
        $("#nextWeekBtn").click(function () {
            var monDate = $("#monday").val();
            var nextMon = dateToStr(addDate(monDate, 7));
            var nextSun = dateToStr(addDate(monDate, 13));
            $("#monday").val(nextMon);
            $("#sunday").val(nextSun);
            $("#test6").val(nextMon + ' - ' + nextSun);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: nextMon,
                    endDate: nextSun
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });

        // 本周一周
        $("#thisWeekBtn").click(function () {
            var now = new Date();
            // 获取周一和周末
            var start = getTime(0, now);
            var end = getTime(-6, now);

            $("#monday").val(start);
            $("#sunday").val(end);
            $("#test6").val(start + ' - ' + end);
            projectTable.reload({
                where: { //设定异步数据接口的额外参数，任意设
                    projectId: $("#searchProject").val(),
                    startDate: start,
                    endDate: end
                }
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });

    });
</script>
</body>
</html>